# coding = utf-8
import os
import numpy as np
from PIL import Image
from PIL import ImageOps
from bitarray import bitarray, util

START_INDEX = 10240


def AsciiFromFile(filename: str, M: int = 0, N: int = 0, toFile: str = None):
    img = Image.open(filename)

    if M == 0 or N == 0:
        M, N = img.size
        M *= 4
        N *= 4

    img = img.resize(size=(M, N), resample=Image.NEAREST)

    img = img.convert("L")
    img = ImageOps.equalize(img)
    img = img.convert("1", dither=Image.NONE)
    # img.show()
    Image2Ascii(img, toFile)


def Image2Ascii(img: Image.Image, toFile: str = None):
    M, N = img.size
    M = M // 2
    N = N // 4
    buf = np.array(img).transpose()
    data = np.zeros(shape=(N, M), dtype=int)
    for i in range(M):
        for j in range(N):
            b = bitarray(8)
            b[0] = buf[2 * i + 0, 4 * j + 0]
            b[1] = buf[2 * i + 0, 4 * j + 1]
            b[2] = buf[2 * i + 0, 4 * j + 2]
            b[3] = buf[2 * i + 1, 4 * j + 0]
            b[4] = buf[2 * i + 1, 4 * j + 1]
            b[5] = buf[2 * i + 1, 4 * j + 2]
            b[6] = buf[2 * i + 0, 4 * j + 3]
            b[7] = buf[2 * i + 1, 4 * j + 3]
            data[j, i] = START_INDEX + util.ba2int(b)

    for i in range(N):
        row = [chr(x) for x in data[i]]
        print("".join(row))

    if toFile:
        with open(toFile, mode="w", encoding="utf8") as f:
            for i in range(N):
                row = [chr(x) for x in data[i]]
                f.write("".join(row))
                f.write("\n")


if __name__ == "__main__":
    rootdir = os.path.abspath("")
    pardir = os.path.join(rootdir, "data")
    outdir = os.path.join(rootdir, "out")
    if not os.path.exists(outdir):
        os.mkdir(outdir)
    for file in os.listdir(pardir):
        try:
            M = 64
            N = M
            base, ext = os.path.splitext(file)
            if ext not in (".png", ".jpg", ".ico", ".bmp", ".gif"):
                continue
            input = os.path.join(pardir, file)
            output = os.path.join(outdir, base + ".txt")
            AsciiFromFile(input, toFile=output)
        except Exception as e:
            print(e)
